﻿using Quartz;
using Quartz.Spi;

namespace QYmall.Core.API.Quartz
{
    /// <summary>
    /// QuartZ主机服务
    /// </summary>
    public class QuartzHostedService : IHostedService
    {
        private readonly ISchedulerFactory _schedulerFactory;
        private readonly IJobFactory _jobFactory;
        private readonly IEnumerable<JobSchedule> _jobSchedules;

        /// <summary>
        /// 依赖注入
        /// </summary>
        public QuartzHostedService(ISchedulerFactory schedulerFactory, IJobFactory jobFactory, IEnumerable<JobSchedule> jobSchedules)
        {
            _schedulerFactory = schedulerFactory;
            _jobFactory = jobFactory;
            _jobSchedules = jobSchedules;
        }

        /// <summary>
        /// 调度容器
        /// </summary>
        public IScheduler? Scheduler { get; set; }

        /// <summary>
        /// 开始任务
        /// </summary>
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            Scheduler = await _schedulerFactory.GetScheduler(cancellationToken);
            Scheduler.JobFactory = _jobFactory;
            foreach (var jobSchedule in _jobSchedules)
            {
                var job = CreateJob(jobSchedule);
                var trigger = CreateTrigger(jobSchedule);
                await Scheduler.ScheduleJob(job, trigger, cancellationToken);
                jobSchedule.JobStatu = JobStatus.Scheduling;
            }
            await Scheduler.Start(cancellationToken);
            foreach (var jobSchedule in _jobSchedules)
            {
                jobSchedule.JobStatu = JobStatus.Running;
            }
        }

        /// <summary>
        /// 停止任务
        /// </summary>
        public async Task StopAsync(CancellationToken cancellationToken)
        {
            if (Scheduler == null) return;
            await Scheduler.Shutdown(cancellationToken);
            foreach (var jobSchedule in _jobSchedules)
            {
                jobSchedule.JobStatu = JobStatus.Stopped;
            }
        }

        /// <summary>
        /// 创建任务
        /// </summary>
        private static IJobDetail CreateJob(JobSchedule schedule)
        {
            var jobType = schedule.JobType;
            return JobBuilder.Create(jobType)
                .WithIdentity(jobType.FullName ?? string.Empty)
                .WithDescription(jobType.Name)
                .Build();
        }

        /// <summary>
        /// 创建触发器
        /// </summary>
        private static ITrigger CreateTrigger(JobSchedule schedule)
        {
            return TriggerBuilder.Create()
                .WithIdentity($"{schedule.JobType.FullName}.trigger")
                .WithCronSchedule(schedule.CronExpression)
                .WithDescription(schedule.CronExpression)
                .Build();
        }
    }
}
